<template>
  <div class="view-container">
    <header-module
      :left-custom="true"
      :padding="true"
    >
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 10px">
            直接应收详情
          </span>
          <span style="font-size: 16px;">{{ customerName }}</span>
        </div>
      </template>
      <template #btn>
        <el-button
          class="border-btn"
          size="small"
          @click="handlBack"
        >返回</el-button>
      </template>
    </header-module>
    <div class="main-content">
      <div class="list-container">
        <el-form
          ref="formRef"
          :inline="true"
          label-position="right"
          size="small"
          class="filter-form-inline"
          label-width="90px"
          :rules="rulers"
          :model="queryParams"
        >
          <el-row :gutter="20">
            <el-col
              :xs="6"
              :lg="8"
              style="max-width: 25%"
            >
              <el-form-item
                label="业务类型"
                style="width: 100%"
                prop="paymentType"
              >
                <el-select
                  v-model="queryParams.paymentType"
                  clearable
                  style="width: 100%"
                  placeholder="业务类型"
                  @change="paymentTypeChange"
                >
                  <el-option
                    key="quanbu"
                    label="全部"
                    value=""
                  />
                  <el-option
                    v-for="(item, idx) in receivableOption"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :xs="6"
              :lg="8"
              style="max-width: 25%"
            >
              <el-form-item
                label="记账日期"
                prop="date"
              >
                <date-range-picker
                  v-model:date="queryParams.date"
                  clearable
                  style="width: 100%"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handlDateChange"
                />
              </el-form-item>
            </el-col>
            <el-col
              v-if="queryParams.paymentType"
              :xs="6"
              :lg="8"
              style="min-width:395px;max-width: 25%"
            >
              <el-form-item
                label="金额"
                style="width:100%"
              >
                <div style="display:flex;">
                  <el-form-item
                    style="margin:0px"
                    prop="minAmount"
                  >
                    <el-input
                      v-model="queryParams.minAmount"
                      placeholder="输入最小金额"
                      oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                    />
                  </el-form-item>
                  <span style="padding: 0px 4px;color: #666">-</span>
                  <el-form-item
                    style="margin:0px"
                    prop="maxAmount"
                  >
                    <el-input
                      v-model="queryParams.maxAmount"
                      placeholder="输入最大金额"
                      oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                    />
                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
            <el-col
              :xs="6"
              :lg="8"
              style="max-width: 25%"
            >
              <el-form-item style="width: 100%">
                <el-button
                  class="border-btn"
                  @click="reset"
                >重置</el-button>
                <el-button
                  type="primary"
                  class="main-btn"
                  @click="updateData"
                >搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col
              :lg="8"
              :xs="6"
              style="max-width: 33.333%"
            >
              <el-form-item
                label="累计营销金额："
                label-width="120px"
              >
                {{ moneyFormat(totalPrice.sumSellAmount) }}元
              </el-form-item>
            </el-col>
            <el-col
              :lg="8"
              :xs="6"
              style="max-width: 33.333%"
            >
              <el-form-item
                label="累计回款金额："
                label-width="120px"
              >
                {{ moneyFormat(totalPrice.sumReturnAmount) }}元
              </el-form-item>
            </el-col>
            <el-col
              :lg="8"
              :xs="6"
              style="max-width: 33.333%"
            >
              <el-form-item
                label="当前应收金额："
                label-width="120px"
              >
                <span v-if="totalPrice.remainAmount>=0">{{ moneyFormat(totalPrice.remainAmount) }}元</span>
                <span v-else>-{{ moneyFormat(Math.abs(totalPrice.remainAmount)) }}元</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <table-view
          header-cell-class-name="table-header"
          :data="tableData"
          border
          :cell-style="cellStyle"
          @row-click="aloneClick"
        >
          <el-table-column
            label="记账时间"
            prop="createdAt"
            header-align="center"
            align="center"
            :width="140"
          >
            <template #default="scope">
              <span>{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="业务类型"
            header-align="center"
            align="center"
            :min-width="100"
          >
            <template #default="scope">
              <div>
                {{ getLabel('receivable_type',scope.row.paymentType) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="金额(元)"
            header-align="center"
            align="right"
            :min-width="120"
          >
            <template #default="scope">
              <span v-if="scope.row.paymentType==='1'">{{ moneyFormat(scope.row.sellAmount) }}</span>
              <span v-if="scope.row.paymentType==='2'">{{ moneyFormat(scope.row.returnAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="应收结余(元)"
            prop="returnAmount"
            header-align="center"
            align="right"
            :min-width="120"
          >
            <template #default="scope">
              <span>{{ moneyFormat(scope.row.remainAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数据来源"
            header-align="center"
            align="center"
            :min-width="100"
          >
            <template #default="scope">
              <span>{{ getLabel('finance_source', scope.row.source) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="关联单据编号"
            prop="relationNumber"
            header-align="center"
            show-overflow-tooltip
            :min-width="140"
          >
            <template #default="scope">
              <my-link
                :underline="false"
                @click="orderDetail(scope.row)"
              >
                {{ scope.row.relationNumber }}
              </my-link>
            </template>
          </el-table-column>
          <el-table-column
            label="操作人"
            prop="creatorName"
            header-align="center"
            align="center"
            :min-width="160"
          >
            <template #default="scope">
              <div style="line-height:20px">
                <span>{{ scope.row.creatorName }}</span>
                <br v-if="scope.row.departmentName">
                <span v-if="scope.row.departmentName">[{{ scope.row.departmentName }}]</span>
              </div>
            </template>
          </el-table-column>
        </table-view>
        <Pagination
          v-model:page="queryParams.page"
          v-model:limit="queryParams.pageSize"
          style="display: flex; justify-content: flex-end"
          :total="total"
          @pagination="handlList"
        />
      </div>
    </div>
    <!--关联单据详情-->
    <detail-drawer
      ref="orderDrawer"
      custom-title
    >
      <template #title>
        <span>关联单据 {{ rowData?.relationNumber }} </span>
      </template>
      <template
        v-if="rowData?.relationId"
        #contents
      >
        <div class="drawer-content">
          <div class="history-list">
            <order-info
              v-if="rowData.source==='order'"
              :id="rowData?.relationId"
              ref="orderInfo"
            />
            <template v-if="rowData.source==='goods'">
              <item-title title="基本信息" />
              <goods-payment-info :id="rowData?.relationId" />
              <item-title title="操作记录" />
              <operation-view
                :id="rowData.id"
                mode="receive_money_split"
              />
            </template>
            <template v-if="rowData?.source==='receive'">
              <item-title title="基本信息" />
              <payee-info :id="rowData?.relationId" />
              <div style="margin-bottom: 20px">
                <item-title title="分账处理结果" />
                <payee-split-info :id="rowData?.relationId" />
              </div>
              <item-title title="操作记录" />
              <operation-view
                :id="rowData?.relationId"
                mode="receive_money"
              />
            </template>
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { crmStore } from '@CRM/store'

export default {
  name: 'ReceivableDetail',
  components: {
    orderInfo: defineAsyncComponent(() =>
      import('@CRM/views/commonView/detailComponents/order/orderInfo.vue')
    ),
    goodsPaymentInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/returnedRecords/goodsPaymentInfo.vue'
      )
    ),
    payeeInfo: defineAsyncComponent(() =>
      import('@CRM/views/returnedRecords/returnedMoney/modules/payeeInfo.vue')
    ),
    payeeSplitInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/returnedRecords/returnedMoney/modules/payeeSplitInfo.vue'
      )
    ),
  },
  setup() {
    const api = inject('api')
    const router = useRouter()
    const route = useRoute()
    const formRef = ref(null)
    const minAmountPass = (rule, value, callback) => {
      if (value) {
        data.queryParams.minAmount = Number(value)
        if (data.queryParams.maxAmount) {
          if (data.queryParams.minAmount <= data.queryParams.maxAmount) {
            callback()
          } else {
            callback(new Error('最小金额不能大于最大金额'))
          }
        } else {
          callback()
        }
      } else {
        if (Number(value) === 0) {
          data.queryParams.minAmount = 0
          callback()
        } else {
          data.queryParams.minAmount = undefined
          callback()
        }
      }
    }
    const maxAmountPass = (rule, value, callback) => {
      if (value) {
        data.queryParams.maxAmount = Number(value)
        if (data.queryParams.minAmount) {
          if (data.queryParams.minAmount <= data.queryParams.maxAmount) {
            callback()
          } else {
            callback(new Error('最大金额不能小于最小金额'))
          }
        } else {
          callback()
        }
      } else {
        if (Number(value) === 0) {
          data.queryParams.maxAmount = 0
          callback()
        } else {
          data.queryParams.maxAmount = undefined
          callback()
        }
      }
    }
    // 搜索对象
    var data = reactive({
      orderDrawer: null,
      rowData: null,
      totalPrice: {},
      customerType: route.query.customerType,
      customerId: Number(route.query.customerId),
      customerName: route.query.customerName,
      queryParams: {
        paymentType: '',
        terminalType: '',
        minAmount: null,
        maxAmount: null,
        date: [],
        start: null,
        end: null,
        pageSize: 20,
        page: 1,
      },
      tableData: [],
      total: 0,
      receivableOption:
        crmStore.getters['dictionary/getDictionary']['receivable_type'],
      rulers: {
        paymentType: [],
        date: [],
        minAmount: [
          { required: false, trigger: 'blur', validator: minAmountPass },
        ],
        maxAmount: [
          { required: false, trigger: 'blur', validator: maxAmountPass },
        ],
      },
    })
    const currentInstance = getCurrentInstance()
    const reset = () => {
      data.queryParams = {
        paymentType: '',
        terminalType: '',
        minAmount: undefined,
        maxAmount: undefined,
        date: [],
        start: null,
        end: null,
        pageSize: 20,
        page: 1,
      }
      updateData()
    }
    // 获取列表
    const handlList = () => {
      var subdata = {
        customerType: data.customerType,
        customerId: data.customerId,
        ...data.queryParams,
      }
      api.returnedAndReceivable.RECEIVABLE_DETAIL_LIST(subdata).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || []
          data.total = res.data.total
        }
      })
    }

    const handlBack = () => {
      router.go(-1)
    }

    const orderDetail = (row) => {
      console.log(row)
      if (row.source === 'flow') {
        router.push({
          path: '/businessFlow/flowImport/details',
          query: { id: row.relationId, type: '1' },
        })
      } else {
        data.rowData = row
        data.orderDrawer.open()
      }
    }

    // 单机表格
    const aloneClick = (row, column, event) => {
      if (column.label === '操作') return
    }

    // 鼠标样式
    const cellStyle = () => {
      return 'cursor:pointer;'
    }
    // 获取金额总数
    const getTotalPrice = () => {
      var subdata = {
        customerType: data.customerType,
        customerId: data.customerId,
        ...data.queryParams,
      }
      api.returnedAndReceivable.RECEIVABLE_DETAIL_PRICE(subdata).then((res) => {
        if (res.code === 0) {
          data.totalPrice = res.data
        }
      })
    }
    const paymentTypeChange = (val) => {
      data.queryParams.paymentType = val
      if (val === '') {
        data.queryParams.minAmount = null
        data.queryParams.maxAmount = null
      }
      updateData()
    }
    // 时间范围变化
    const handlDateChange = (val) => {
      console.log(val)
      if (val && val.length) {
        data.queryParams.start = val[0]
        data.queryParams.end = val[1]
      } else {
        data.queryParams.start = null
        data.queryParams.end = null
      }
      updateData()
    }
    const updateData = () => {
      getTotalPrice()
      handlList()
    }

    onMounted(() => {
      getTotalPrice()
      handlList()
    })

    return {
      formRef,
      ...toRefs(data),
      handlList,
      handlBack,
      aloneClick,
      cellStyle,
      reset,
      updateData,
      handlDateChange,
      paymentTypeChange,
      orderDetail,
    }
  },
}
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
